package javaInterview;

import java.io.*;

public class SerializationDemo {
    public static void main(String[] args) {
        // 创建一个User对象
        User user = new User("张三", 25);
        System.out.println("原始对象: " + user);
        
        // 序列化对象到文件
        try {
            FileOutputStream fileOut = new FileOutputStream("user.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(user);
            out.close();
            fileOut.close();
            System.out.println("对象已序列化并保存到user.ser文件");
        } catch (IOException i) {
            i.printStackTrace();
        }
        
        // 从文件反序列化对象
        try {
            FileInputStream fileIn = new FileInputStream("user.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            User deserializedUser = (User) in.readObject();
            in.close();
            fileIn.close();
            System.out.println("对象已反序列化: " + deserializedUser);
        } catch (IOException i) {
            i.printStackTrace();
        } catch (ClassNotFoundException c) {
            System.out.println("User class not found");
            c.printStackTrace();
        }
        
        // 演示transient关键字的使用
        demonstrateTransient();
    }
    
    private static void demonstrateTransient() {
        System.out.println("\n=== 演示transient关键字 ===");
        UserWithTransient user = new UserWithTransient("李四", 30, "secretPassword");
        System.out.println("序列化前的对象: " + user);
        
        try {
            // 序列化
            FileOutputStream fileOut = new FileOutputStream("user_transient.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(user);
            out.close();
            fileOut.close();
            
            // 反序列化
            FileInputStream fileIn = new FileInputStream("user_transient.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            UserWithTransient deserializedUser = (UserWithTransient) in.readObject();
            in.close();
            fileIn.close();
            
            System.out.println("反序列化后的对象: " + deserializedUser);
            System.out.println("注意password字段变为null，因为它被transient修饰");
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}